<template>
  <div class="consultation-manage-container">
    <h2 class="page-title">问诊单管理</h2>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <el-input 
            v-model="queryParams.patientSearch" 
            placeholder="输入患者姓名或手机号" 
            clearable 
            @keyup.enter="handleQuery"
          />
        </div>
        
        <div class="filter-item">
          <span class="label">问诊状态</span>
          <el-select v-model="queryParams.consultationStatus" placeholder="请选择..." clearable>
            <el-option label="全部" :value="0" />
            <el-option label="审核通过" :value="1" />
            <el-option label="未通过" :value="2" />
          </el-select>
        </div>
        
        <div class="filter-item">
          <span class="label">问诊方式</span>
          <el-select v-model="queryParams.consultationType" placeholder="请选择..." clearable>
            <el-option label="全部" :value="0" />
            <el-option label="图文问诊" :value="1" />
            <el-option label="视频问诊" :value="2" />
            <el-option label="电话问诊" :value="3" />
          </el-select>
        </div>
      </div>
      
      <div class="filter-row">
        <div class="filter-item">
          <span class="label">问诊来源</span>
          <el-select v-model="queryParams.consultationSource" placeholder="请选择..." clearable>
            <el-option label="全部" :value="0" />
            <el-option label="视频问诊" :value="1" />
            <el-option label="图文问诊" :value="2" />
            <el-option label="电话问诊" :value="3" />
            <el-option label="极速图文" :value="4" />
            <el-option label="极速电话" :value="5" />
            <el-option label="复诊开药" :value="6" />
          </el-select>
        </div>
        
        <div class="filter-item date-range">
          <span class="label">日期</span>
          <el-date-picker
            v-model="queryParams.startTime"
            type="datetime"
            placeholder="开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
          />
          <span class="separator">—</span>
          <el-date-picker
            v-model="queryParams.endTime"
            type="datetime"
            placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
          />
        </div>
        
        <div class="filter-item">
          <el-button type="primary" @click="handleQuery">筛选</el-button>
        </div>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-section">
      <!-- 标签页 -->
      <div class="tabs">
        <div 
          v-for="(tab, index) in tabs" 
          :key="index" 
          :class="['tab-item', {'active': queryParams.orderStatus === tab.value}]"
          @click="handleTabChange(tab.value)"
        >
          {{ tab.label }}
        </div>
      </div>
      
      <!-- 表格 -->
      <div class="table-container">
        <div class="table-actions">
          <el-checkbox v-model="selectAll" @change="handleSelectAllChange">全选</el-checkbox>
          <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchDelete">批量删除</el-button>
          <span class="record-info">共{{ total }}页/{{ total }}条数据</span>
        </div>
        
        <el-table
          v-loading="loading"
          :data="consultationList"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="提交时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.submitTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="patient" label="患者" align="center" />
          <el-table-column prop="department" label="科室" align="center" />
          <el-table-column prop="doctor" label="医生" align="center" />
          <el-table-column prop="consultationType" label="方式" align="center">
            <template #default="scope">
              {{ getConsultationTypeText(scope.row.consultationType) }}
            </template>
          </el-table-column>
          <el-table-column prop="consultationSource" label="来源" align="center">
            <template #default="scope">
              {{ getConsultationSourceText(scope.row.consultationSource) }}
            </template>
          </el-table-column>
          <el-table-column label="问诊费" align="center">
            <template #default="scope">
              {{ scope.row.consultationFee }} 元
            </template>
          </el-table-column>
          <el-table-column label="订单状态" align="center">
            <template #default="scope">
              <el-tag :type="getStatusTypeByCode(scope.row.orderStatus)">
                {{ getOrderStatusText(scope.row.orderStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" link @click="handleView(scope.row)">查看订单</el-button>
              <el-button 
                v-if="scope.row.orderStatus === 3 || scope.row.orderStatus === '已完成'" 
                type="success" 
                link 
                @click="handleViewRecord(scope.row)"
              >问诊记录</el-button>
              <el-button 
                v-if="scope.row.orderStatus === 4 || scope.row.orderStatus === '已取消'" 
                type="danger" 
                link 
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageIndex"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 修改查看订单对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="getDetailTitle()" 
      width="800px" 
      destroy-on-close
    >
      <div v-if="orderDetail" class="order-detail">
        <!-- 标签页切换 -->
        <el-tabs v-model="activeTabName">
          <el-tab-pane label="患者信息" name="patientInfo">
            <div class="detail-section">
              <div class="detail-grid">
                <div class="detail-item">
                  <span class="label">患者姓名：</span>
                  <span>{{ orderDetail.patient?.name }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">性别：</span>
                  <span>{{ orderDetail.patient?.gender }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">年龄：</span>
                  <span>{{ orderDetail.patient?.age }} 岁</span>
                </div>
                <div class="detail-item">
                  <span class="label">手机号：</span>
                  <span>{{ orderDetail.patient?.phone }}</span>
                </div>
                <div class="detail-item full-width">
                  <span class="label">预约时间：</span>
                  <span>{{ formatDateTime(orderDetail.patient?.appointmentTime) }}</span>
                </div>
                <div class="detail-item full-width">
                  <span class="label">提交时间：</span>
                  <span>{{ formatDateTime(orderDetail.patient?.submitTime) }}</span>
                </div>
                <div class="detail-item full-width">
                  <span class="label">病情描述：</span>
                  <span>{{ orderDetail.patient?.diseaseDescription || '无' }}</span>
                </div>
                <div class="detail-item full-width">
                  <span class="label">就诊情况：</span>
                  <span>{{ orderDetail.patient?.medicalSituation || '无' }}</span>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="订单信息" name="orderInfo">
            <div class="detail-section">
              <div class="detail-grid">
                <div class="detail-item">
                  <span class="label">订单编号：</span>
                  <span>{{ orderDetail.orderInfo?.orderNo }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">订单类型：</span>
                  <span>{{ orderDetail.orderInfo?.orderType }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">订单状态：</span>
                  <span>
                    <el-tag :type="getStatusTypeByCode(orderDetail.orderInfo?.orderStatus || '')">
                      {{ orderDetail.orderInfo?.orderStatus }}
                    </el-tag>
                  </span>
                </div>
                <div class="detail-item">
                  <span class="label">创建时间：</span>
                  <span>{{ formatDateTime(orderDetail.orderInfo?.createTime) }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">应付金额：</span>
                  <span>￥{{ orderDetail.orderInfo?.payableAmount }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">优惠金额：</span>
                  <span>￥{{ orderDetail.orderInfo?.couponAmount }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">实际支付：</span>
                  <span>￥{{ orderDetail.orderInfo?.actualPayment }}</span>
                </div>
                
                <!-- 根据订单状态显示不同内容 -->
                <template v-if="orderDetail.orderInfo?.orderStatus === '待支付'">
                  <!-- 待支付订单无额外信息 -->
                </template>
                
                <template v-if="['已完成', '进行中', '已退诊'].includes(orderDetail.orderInfo?.orderStatus || '')">
                  <div class="detail-item">
                    <span class="label">支付方式：</span>
                    <span>{{ orderDetail.orderInfo?.paymentMethod || '-' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">支付时间：</span>
                    <span>{{ formatDateTime(orderDetail.orderInfo?.paymentTime) || '-' }}</span>
                  </div>
                </template>
                
                <template v-if="['已退诊'].includes(orderDetail.orderInfo?.orderStatus || '')">
                  <div class="detail-item">
                    <span class="label">退款金额：</span>
                    <span>￥{{ orderDetail.orderInfo?.refundAmount || 0 }}</span>
                  </div>
                  <div class="detail-item full-width">
                    <span class="label">退诊原因：</span>
                    <span>{{ orderDetail.orderInfo?.refundReason || '无' }}</span>
                  </div>
                </template>
              </div>
            </div>
          </el-tab-pane>
          
          <!-- 只在已完成的订单中显示问诊信息 -->
          <el-tab-pane v-if="orderDetail.orderInfo?.orderStatus === '已完成' && orderDetail.consultInfo" label="问诊信息" name="consultInfo">
            <div class="detail-section">
              <div class="detail-grid">
                <div class="detail-item">
                  <span class="label">问诊时间：</span>
                  <span>{{ formatDateTime(orderDetail.consultInfo?.consultationTime) }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">通话时长：</span>
                  <span>{{ orderDetail.consultInfo?.callDuration || '-' }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">患者评分：</span>
                  <span class="rating-stars">{{ getRatingStars(orderDetail.consultInfo?.patientRating) }}</span>
                </div>
                <div class="detail-item full-width">
                  <span class="label">患者评价：</span>
                  <span>{{ orderDetail.consultInfo?.patientComment || '无评价' }}</span>
                </div>
              </div>
            </div>
            
            <!-- 问诊记录 -->
            <div v-if="orderDetail.consultInfo?.consultRecords && orderDetail.consultInfo.consultRecords.length > 0" class="detail-section">
              <h3 class="section-title">问诊记录</h3>
              <div class="consult-records">
                <div 
                  v-for="record in orderDetail.consultInfo.consultRecords" 
                  :key="record.id"
                  :class="['record-item', record.senderType === '患者' ? 'patient-record' : 'doctor-record']"
                >
                  <div class="record-time">{{ formatDateTime(record.time) }}</div>
                  <div class="record-content">
                    <div class="record-type">{{ record.type }}</div>
                    <div class="record-text">{{ record.content }}</div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">返回</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { axiosrzsh } from '@/http/axiosRead'
import type { FormInstance } from 'element-plus'

// 定义问诊订单的接口类型
interface ConsultationOrder {
  submitTime: string
  patient: string
  department: string
  doctor: string
  consultationType: string | number
  consultationSource: string | number
  consultationFee: number
  orderStatus: string | number
  orderNo: string
}

// 新增问诊订单详情接口
interface PatientInfo {
  name: string
  gender: string
  age: number
  phone: string
  diseaseDescription: string
  medicalSituation: string
  appointmentTime: string
  submitTime: string
}

interface OrderInfo {
  orderNo: string
  orderType: string
  orderStatus: string
  payableAmount: number
  couponAmount: number
  actualPayment: number
  createTime: string
  paymentMethod?: string
  paymentTime?: string
  refundReason?: string
  refundAmount?: number
}

interface ConsultRecord {
  id: number
  time: string
  type: string
  content: string
  senderType: string
}

interface ConsultInfo {
  consultationTime?: string
  callDuration?: string
  patientRating?: number
  patientComment?: string
  consultRecords?: ConsultRecord[]
}

interface ConsultationDetail {
  patient?: PatientInfo
  orderInfo?: OrderInfo
  consultInfo?: ConsultInfo
}

// 定义查询参数
const queryParams = reactive({
  patientSearch: '',
  consultationStatus: 0,
  consultationType: 0,
  consultationSource: 0,
  startTime: '',
  endTime: '',
  orderStatus: 0, // 默认查询全部
  pageIndex: 1,
  pageSize: 10
})

// 标签页配置
const tabs = [
  { label: '全部', value: 0 },
  { label: '待支付', value: 1 },
  { label: '进行中', value: 2 },
  { label: '已完成', value: 3 },
  { label: '已取消', value: 4 },
  { label: '已退诊', value: 5 }
]

// 数据列表
const consultationList = ref<ConsultationOrder[]>([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const currentOrder = ref<ConsultationOrder | null>(null)

// 选择行相关
const selectAll = ref(false)
const selectedRows = ref<ConsultationOrder[]>([])

// 获取问诊订单列表
const getConsultationList = async () => {
  loading.value = true
  try {
    const response = await axiosrzsh.get('/ConsultationOrder', {
      params: queryParams
    })
    if (response.data.code === 200) {
      consultationList.value = response.data.pageData || []
      total.value = response.data.totaCount || 0
    } else {
      ElMessage.error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取问诊订单数据失败:', error)
    ElMessage.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string | undefined): string => {
  if (!dateTimeStr) return '-'
  const date = new Date(dateTimeStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
}

// 获取问诊方式文本
const getConsultationTypeText = (type: string | number): string => {
  // 如果传入的是字符串，直接返回
  if (typeof type === 'string') {
    return type;
  }
  
  // 如果传入的是数字，按编码转换
  switch (type) {
    case 1: return '图文问诊'
    case 2: return '视频问诊'
    case 3: return '电话问诊'
    default: return '未知方式'
  }
}

// 获取问诊来源文本
const getConsultationSourceText = (source: string | number): string => {
  // 如果传入的是字符串，直接返回
  if (typeof source === 'string') {
    return source;
  }
  
  // 如果传入的是数字，按编码转换
  switch (source) {
    case 1: return '视频问诊'
    case 2: return '图文问诊'
    case 3: return '电话问诊'
    case 4: return '极速图文'
    case 5: return '极速电话'
    case 6: return '复诊开药'
    default: return '未知来源'
  }
}

// 获取订单状态文本
const getOrderStatusText = (status: string | number): string => {
  // 如果传入的是字符串，直接返回
  if (typeof status === 'string') {
    return status;
  }
  
  // 如果传入的是数字，按编码转换
  switch (status) {
    case 1: return '待支付'
    case 2: return '进行中'
    case 3: return '已完成'
    case 4: return '已取消'
    case 5: return '已退诊'
    default: return '未知状态'
  }
}

// 获取状态显示类型
const getStatusTypeByCode = (status: string | number): string => {
  // 如果传入的是字符串，根据字符串内容判断
  if (typeof status === 'string') {
    if (status === '待支付') return 'warning'
    if (status === '进行中') return 'primary'
    if (status === '已完成') return 'success'
    if (status === '已取消') return 'info'
    if (status === '已退诊') return 'danger'
    return 'info'
  }
  
  // 如果传入的是数字，按编码判断
  switch (status) {
    case 1: return 'warning' // 待支付
    case 2: return 'primary' // 进行中
    case 3: return 'success' // 已完成
    case 4: return 'info'    // 已取消
    case 5: return 'danger'  // 已退诊
    default: return 'info'
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageIndex = 1
  getConsultationList()
}

// 处理标签页切换
const handleTabChange = (status: number) => {
  queryParams.orderStatus = status
  handleQuery()
}

// 处理分页大小改变
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  getConsultationList()
}

// 处理分页页码改变
const handleCurrentChange = (page: number) => {
  queryParams.pageIndex = page
  getConsultationList()
}

// 处理全选变更
const handleSelectAllChange = (val: boolean) => {
  if (val) {
    selectedRows.value = [...consultationList.value]
  } else {
    selectedRows.value = []
  }
}

// 处理选择行变更
const handleSelectionChange = (rows: ConsultationOrder[]) => {
  selectedRows.value = rows
  selectAll.value = rows.length === consultationList.value.length && rows.length > 0
}

// 处理查看详情
const handleView = async (row: ConsultationOrder) => {
  try {
    loading.value = true
    const response = await axiosrzsh.get(`/ConsultationOrder/${row.orderNo}`)
    if (response.data.code === 200) {
      orderDetail.value = response.data.data
      dialogVisible.value = true
      // 默认显示第一个标签页
      activeTabName.value = 'patientInfo'
    } else {
      ElMessage.error(response.data.msg || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 处理查看问诊记录
const handleViewRecord = (row: ConsultationOrder) => {
  ElMessage.info(`查看问诊记录: ${row.orderNo}`)
  // 此处可以跳转到问诊记录页面或打开问诊记录对话框
}

// 处理删除
const handleDelete = (row: ConsultationOrder) => {
  ElMessageBox.confirm('确认删除此订单?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里添加删除API调用
    ElMessage.success('删除成功')
    getConsultationList()
  }).catch(() => {})
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里添加批量删除API调用
    ElMessage.success('批量删除成功')
    getConsultationList()
  }).catch(() => {})
}

// 页面加载时获取数据
onMounted(() => {
  getConsultationList()
})

// 添加变量定义
const orderDetail = ref<ConsultationDetail | null>(null)
const activeTabName = ref('patientInfo')

// 获取详情对话框标题
const getDetailTitle = (): string => {
  if (!orderDetail.value || !orderDetail.value.orderInfo) return '订单详情'
  return `订单详情-${orderDetail.value.orderInfo.orderStatus}`
}

// 获取星级评分展示
const getRatingStars = (rating: number | undefined): string => {
  if (!rating) return ''
  return '★'.repeat(rating)
}
</script>

<style scoped>
.consultation-manage-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f7f7f7;
  border-radius: 5px;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 10px;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.filter-item {
  margin-right: 15px;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.filter-item .label {
  margin-right: 8px;
  white-space: nowrap;
}

.date-range {
  display: flex;
  align-items: center;
}

.separator {
  margin: 0 8px;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.tab-item {
  padding: 10px 20px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  border-bottom: 2px solid transparent;
}

.tab-item.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

.table-container {
  margin-bottom: 20px;
}

.table-actions {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.record-info {
  margin-left: auto;
  color: #666;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.order-detail {
  padding: 10px 0;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.detail-section {
  margin-bottom: 20px;
  background-color: #f9f9f9;
  border-radius: 5px;
  padding: 15px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.detail-item {
  line-height: 24px;
}

.detail-item .label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.full-width {
  grid-column: 1 / -1; /* 跨两列 */
}

.rating-stars {
  color: #ff9800; /* 星星颜色 */
  font-size: 16px;
}

.consult-records {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eaeaea;
}

.record-item {
  display: flex;
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.record-item.patient-record {
  flex-direction: row-reverse; /* 患者记录靠右 */
}

.record-item.patient-record .record-time {
  text-align: right;
}

.record-item.patient-record .record-content {
  text-align: right;
}

.record-item.patient-record .record-type {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 12px;
  margin-left: auto;
}

.record-item.doctor-record .record-type {
  background-color: #e1f3d8;
  color: #67c23a;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 12px;
}

.record-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.record-content {
  display: flex;
  align-items: flex-start;
}

.record-type {
  font-weight: bold;
  margin-right: 8px;
}

.record-text {
  flex-grow: 1;
  word-break: break-word;
  line-height: 1.5;
}
</style> 